<template>
  <div class="user-profile">
    <input type="file" hidden ref="file" @change="onChange" /><!-- 头像图片上传 -->
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" title="个人信息" left-arrow @click-left="$router.back()" />
    <!-- /导航栏 -->
    <van-cell title="头像" is-link @click="$refs.file.click()">
      <van-image class="avatar" fit="cover" round :src="user.photo" />
    </van-cell>
    <van-cell title="昵称" @click="isShowUpdateName = true" :value="user.name" is-link />
    <van-cell title="性别" @click="isGenderShow = true" :value="user.gender ? '女' : '男'" is-link />
    <van-cell title="生日" @click="isBirthdyShow = true" :value="user.birthday || '1977-00-00'" is-link />

    <!-- 修改昵称弹层 -->
    <van-popup v-model="isShowUpdateName" :style="{ background: '#f5f7f9' }" position="bottom">
      <update-name @close="isShowUpdateName = false" :user="user"></update-name>
    </van-popup>
    <!-- 修改性别弹层 -->
    <van-popup v-model="isGenderShow" position="bottom">
      <update-gender @close="isGenderShow = false" :gender="user.gender" @update="user.gender = user.gender === 0 ? 1 : 0"></update-gender>
    </van-popup>
    <!-- 修改生日弹层 -->
    <van-popup v-model="isBirthdyShow" position="bottom">
      <update-birthday @close="isBirthdyShow = false" :birthday="user.birthday" @update="user.birthday = $event"></update-birthday>
    </van-popup>
    <!-- 修改头像弹层 -->
    <van-popup v-model="isPhotoShow" position="bottom">
      <update-photo v-if="isPhotoShow" :imgSrc="imgSrc" @close="isPhotoShow = false" @update="user.photo = $event"></update-photo>
    </van-popup>
  </div>
</template>

<script>
import { getUserProfile } from '@/api/user'
import UpdateName from './components/update-name.vue' // 修改昵称组件
import UpdateGender from './components/update-gender.vue' // 修改性别组件
import UpdateBirthday from './components/update-birthday' // 修改生日组件
import UpdatePhoto from './components/update-photo.vue'
export default {
  name: 'UserProfile',
  components: { UpdateName, UpdateGender, UpdateBirthday, UpdatePhoto },
  data () {
    return {
      user: {}, // 存放用户信息
      isShowUpdateName: false,
      isGenderShow: false,
      isBirthdyShow: false,
      isPhotoShow: false,
      imgSrc: null
    }
  },
  created () {
    this.loadProfile()
  },
  methods: {
    async loadProfile () {
      try {
        const { data: res } = await getUserProfile()
        this.user = res.data
        console.log(this.user)
      } catch (err) {
        this.$toast('获取数据失败')
      }
    },
    onChange () {
      this.isPhotoShow = true
      console.log(this.$refs.file.files)
      // 图片临时存放在本地的blob协议地址
      console.log(window.URL.createObjectURL(this.$refs.file.files[0]))
      this.imgSrc = window.URL.createObjectURL(this.$refs.file.files[0])
      this.$refs.file.value = ''
    }
  }
}
</script>

<style scoped lang="less">
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
}
</style>
